package me.xiaoyan.ehr.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import me.xiaoyan.ehr.config.annotation.OperationLog;
import me.xiaoyan.ehr.po.SysLog;
import me.xiaoyan.ehr.service.SysLogService;
import me.xiaoyan.ehr.util.IPUtil;
import me.xiaoyan.ehr.util.StringUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 统一访问日志处理
 */
@Aspect
@Component
public class AppLog {
    private SysLogService sysLogService;

    @Autowired
    public void setSysLogService(SysLogService sysLogService) {
        this.sysLogService = sysLogService;
    }

    @Pointcut("@annotation(me.xiaoyan.ehr.config.annotation.OperationLog)")
    public void operationLogPointCut() {
    }


    /**
     * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
     */
    @Pointcut("execution(* me.xiaoyan.ehr.controller..*.*(..))")
    public void operationExceptionLogPointCut() {
    }

    @AfterReturning(value = "operationLogPointCut()", returning = "keys")
    public void saveOperLog(JoinPoint joinPoint, Object keys) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取请求参数
            Map<String, String> paramMap = StringUtil.convertParamMap(request.getParameterMap());
            //
            ObjectMapper json = new ObjectMapper();
            // 将请求参数转换成json
            String params = json.writeValueAsString(paramMap);
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;

            SysLog log = new SysLog();

            // TODO
            log.setUid(-1); // 操作员ID
            //获取用户浏览器的标识
            log.setUserAgent(request.getHeader("User-Agent"));
            // 请i去参数
            log.setRequestParams(params);
            log.setRequestMethod(methodName); // 请求方法
            // 获取客户端的ip
            log.setRequestIp(IPUtil.getIpAddr(request));
            log.setProcessStatus(1); // TODO 处理成功
            // 获取操作记录
            OperationLog opLog = method.getAnnotation(OperationLog.class);
            if (opLog != null) {
                log.setModule(opLog.value());
                log.setRemark(opLog.description());
            }
            sysLogService.save(log);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
